﻿using Framework.Utility.Helper;
using Framework.Utility.ViewModels;
using Microsoft.Extensions.Logging;
using MonitorCode.Hangfire;
using MySql.Data.MySqlClient;
using System.Data;
using System.Text;

namespace MonitorCode.DBCode
{
    public class MySqlDBService : IDBService
    { 
        private readonly string _connStr;
        public MySqlDBService(DBLinkModel model)
        { 
            _connStr = $"server={model.DBHostName};userid={model.UserName};pwd={model.Password};port={model.Port};database={model.DatabaseName};Allow User Variables=True;sslMode=None";

        }

        public TData ExecuteNonQuery(string sql)
        {  
            var count = MySqlUtilsHelper.ExecuteNonQuery(_connStr, CommandType.Text, sql); 
            return new TData(ResultTag.success, "", count);
        }

        public TData GetCountBySql(string sql)
        {
            DataTable dt = MySqlUtilsHelper.GetDataTable(_connStr, CommandType.Text, sql);
            var ret = dt.Rows.Count;
            return new TData(ResultTag.success,"",ret);
        }

        public TData GetListBySql<T>(string sql)
        {
            //sbr.Append("UPDATE test_table SET ");
            //sbr.Append("name='13', ");
            //sbr.Append("password='333' ");
            //sbr.Append("WHERE id=@id;");
            //cmdText = sbr.ToString();
            //MySqlParameter idParm = new MySqlParameter("@id", 2);
            DataTable dt = MySqlUtilsHelper.GetDataTable(_connStr, CommandType.Text, sql); 
            var list =  dt.ConvertDataTableToList<T>();
            TData data = new TData(ResultTag.success);
            data.data =list;
            data.total= list.Count; 
            return data;
        }

        public List<T> GetDataListBySql<T>(string sql)
        { 
            DataTable dt = MySqlUtilsHelper.GetDataTable(_connStr, CommandType.Text, sql);
            return dt.ConvertDataTableToList<T>(); 
        }
    }
}